package com.njust.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.njust.common.Const;
import com.njust.dataobject.*;
import com.njust.form.RequestGear;
import com.njust.form.TableQueryByState;
import com.njust.mapper.*;
import com.njust.service.TablesService;
import com.njust.service.TrainService;
import com.njust.utils.CompareUtil;
import com.njust.utils.DateUtil;
import com.njust.utils.PageUtils;
import com.njust.utils.StringUtil;
import com.njust.vo.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Create by User: HorseChestnut
 * Date: 2018-01-06
 */
@Slf4j
@Service
public class TablesServiceImpl implements TablesService {

    @Autowired
    TrainInfoMapper trainInfoMapper;
    @Autowired
    TrainDataMapper trainDataMapper;
    @Autowired
    MotorInfoMapper motorInfoMapper;
    @Autowired
    GearInfoMapper gearInfoMapper;

    @Autowired
    private TrainService trainService;

    @Autowired
    private TrainParamMapper trainParamMapper;
    /**
     * @param table
     * @return 返回相关列车信息。
     */
    @Override
    public ResultVO getTrainInfos(TableQueryByState table) throws ParseException {
        TrainParam trainParam = new TrainParam();
        // 定义
        PageHelper.startPage(table.getPage(),table.getPageSize());
        TrainInfoExample example = new TrainInfoExample();
        TrainInfoExample.Criteria criteria= example.createCriteria();
        criteria.andTrainDateBetween(DateUtil.String2Date(table.getStartTime()),
                DateUtil.String2Date(table.getEndTime()));

        if(table.getTrainStateList().size()!=0){
            //多个状态查询的封装
            criteria.andTrainStateIn(table.getTrainStateList());
        }
        //车号为空的话或者不为all的话  默认为全部车号
        if((table.getTrainId() != null) && (!table.getTrainId().equals("all"))){
            criteria.andTrainIdEqualTo(table.getTrainId());
        }
        if(table.getTrainStation() != null){
            criteria.andTrainStationEqualTo(table.getTrainStation());
        }
        if(table.getTrainDirection() != null&&(!table.getTrainDirection().equals(new Integer(2)))){
            criteria.andTrainDirectionEqualTo(table.getTrainDirection());
        }else{
               List<Integer> trainDirectionList = new ArrayList<>();
               trainDirectionList.add(1);
               trainDirectionList.add(0);
               criteria.andTrainDirectionIn(trainDirectionList);
        }
        example.setOrderByClause("train_date DESC");

        List<TrainInfo> infos = trainInfoMapper.selectByExample(example);
        PageInfo<TrainInfo> pageInfo=new PageInfo<>(infos);
        if(infos.size() == 0){
            log.info("查询不到指定条件的记录，请求的条件为：{}",table);
            return ResultVO.createByErrorMessage("无数据");
        }
        //PageInfo<TrainInfo> pageBean = new PageInfo<>(infos);

        List<TrainDataVO> dataVOList = new ArrayList<>();
        //对得到的列车信息进行查询和封装
        for(TrainInfo info : infos){
            //得到列车记录号
            Long trainOnlyid = info.getTrainOnlyid();
            //定义实际返回的TrainDataVo类对象。
            TrainDataVO trainDataVO = new TrainDataVO();
            trainDataVO.setControlNum(info.getControlNum());
            trainDataVO.setTrainDate(DateUtil.Date2String(info.getTrainDate()));
            trainDataVO.setTrainDirection(info.getTrainDirection());//列车的行驶方向
            trainDataVO.setTrainOnlyid(trainOnlyid);
            trainDataVO.setTrainId(info.getTrainId());
            trainDataVO.setTrainState(info.getTrainState());

            // 通过相关trainOnlyId 获取详细的TrainData
            TrainData trainData = trainDataMapper.selectByPrimaryKey(trainOnlyid);
            if(trainData == null){
                log.info("有列车记录，但没有列车详细记录,列车号为{}：",info.getTrainId());
                return ResultVO.createByErrorMessage("无数据");
            }
            // 封装的数据注入trainData中有的数据。
            //trainDataVO.setTempAverage(trainData.getTempAverage());
            //trainDataVO.setLgapAverage(trainData.getLgapAverage());
           // trainDataVO.setRgapAverage(trainData.getRgapAverage());
           // trainDataVO.setLslotAverage(trainData.getLslotAverage());
            //trainDataVO.setRslotAverage(trainData.getRslotAverage());
            //添加排障器值和排障器状态设置
            trainDataVO.setLpilotMin(trainData.getLpilotMin());
            trainDataVO.setRpilotMin(trainData.getRpilotMin());
            //在此处获取trainParam 进行比较比较好，但是浪费时间和空间
            trainParam = trainParamMapper.findByUdFlag(trainDataVO.getTrainDirection());
            if(trainParam==null){
                return ResultVO.createByErrorMessage("请先设置阈值");
            }

            if(trainDataVO.getLpilotMin()!=null){
                //进行相应颜色的设置
                Integer result = CompareUtil.compare(Const.PILOT,trainParam.getPilotWarm(),trainParam.getPilotAlarm(),trainDataVO.getLpilotMin());
                trainDataVO.setLpilotMinStatus(result);
            }
            if(trainDataVO.getRpilotMin()!=null){
                //进行相应颜色的设置
                Integer result = CompareUtil.compare(Const.PILOT,trainParam.getPilotWarm(),trainParam.getPilotAlarm(),trainDataVO.getRpilotMin());
                trainDataVO.setRpilotMinStatus(result);
            }

            MotorInfoExample motorExample = new MotorInfoExample();
            MotorInfoExample.Criteria motorCriteria = motorExample.createCriteria();
            motorCriteria.andTrainOnlyidEqualTo(trainOnlyid);
            List<MotorInfo> motors = motorInfoMapper.selectByExample(motorExample);
            if(motors == null){
                log.info("有列车记录，但没有相关的电机记录。列车号为{}",info.getTrainId());
                return ResultVO.createByErrorMessage("无数据");
            }
            //分装齿的数据
            trainService.assembleGearData(motors,trainParam,trainData,trainDataVO);
            dataVOList.add(trainDataVO);
        }
        PageResultVo pageResultVo = new PageResultVo();
        PageUtils.pageUtil(pageInfo,pageResultVo);
        pageResultVo.setList(dataVOList);
        return ResultVO.createBySuccess(pageResultVo);
    }

    /**
     * 通过trainid 获取 8个motor  并获取所有的相关最大最小的齿轮。
     * @param trainOnlyid
     * @return
     */
    @Override
    public List<MotorVO> getMotorInfoByTrainId(Long trainOnlyid){
        List<MotorVO> motorVOS = new ArrayList<>();
        MotorInfoExample motorExample = new MotorInfoExample();
        MotorInfoExample.Criteria motorCriteria = motorExample.createCriteria();
        //motorCriteria.andTrainIdEqualTo(trainId);
        motorCriteria.andTrainOnlyidEqualTo(trainOnlyid);
        List<MotorInfo> motors = motorInfoMapper.selectByExample(motorExample);
        for(MotorInfo motorInfo : motors){
            MotorVO motorVO = new MotorVO();
            //motorVO.setTempAverage(motorInfo.getTempAverage());
            motorVO.setLgapMin(StringUtil.
                    changeChi(gearInfoMapper.findByMotorIdAndGearNum(motorInfo.getMotorId()
                            ,motorInfo.getLgapMin()).getLgapValue(),motorInfo.getLgapMin()));
            motorVO.setRgapMin(StringUtil.
                    changeChi(gearInfoMapper.findByMotorIdAndGearNum(motorInfo.getMotorId()
                            ,motorInfo.getRgapMin()).getRgapValue(),motorInfo.getRgapMin()));
            motorVO.setLslotMin(StringUtil.
                    changeCao(gearInfoMapper.findByMotorIdAndGearNum(motorInfo.getMotorId()
                            ,motorInfo.getLslotMin()).getLgapValue(),motorInfo.getLslotMin()));
            motorVO.setRslotMin(StringUtil.
                    changeCao(gearInfoMapper.findByMotorIdAndGearNum(motorInfo.getMotorId()
                            ,motorInfo.getRslotMin()).getLgapValue(),motorInfo.getRslotMin()));
            //motorVO.setMotorNum(motorInfo.getMotorNum());
            motorVOS.add(motorVO);
        }

        return motorVOS;
    }
    /**
     * 根据gearid去查询齿轮和槽戏的值。
     * @param gearId
     * @return
     */
    @Override
    public GearInfo getGearByGearId(Long gearId){
        return gearInfoMapper.selectByPrimaryKey(gearId);
    }
    /**
     * 根据条件查询相关齿的信息趋势
     * @param requestGear
     * @return
     */
    @Override
    public ResultVO getGearInfoByCondition(RequestGear requestGear) throws ParseException {

        List<GearResponse> gearList = new ArrayList<>();
        if(requestGear.getPage()==null && requestGear.getPageSize()==null){
            // 定义
            TrainInfoExample example = new TrainInfoExample();
            TrainInfoExample.Criteria criteria= example.createCriteria();

            // TODO: 2018/1/9 时间的判断 传过来的内容进行判断
            criteria.andTrainDateBetween(DateUtil.String2Date(requestGear.getStartTime()),
                    DateUtil.String2Date(requestGear.getEndTime()));

            if(requestGear.getTrainId() != null){
                criteria.andTrainIdEqualTo(requestGear.getTrainId());
            }

            if(requestGear.getTrainDirection() != null){
                criteria.andTrainDirectionEqualTo(requestGear.getTrainDirection());
            }
            List<TrainInfo> infos = trainInfoMapper.selectByExample(example);
            if(infos.size()==0){
                return ResultVO.createByErrorMessage("无数据");
            }
            assembleGearTrendencyInfo(requestGear, gearList, infos);
            return ResultVO.createBySuccess(gearList);
        }else {
            // 定义
            PageHelper.startPage(requestGear.getPage(),requestGear.getPageSize());
            TrainInfoExample example = new TrainInfoExample();
            TrainInfoExample.Criteria criteria= example.createCriteria();

            // TODO: 2018/1/9 时间的判断 传过来的内容进行判断
            criteria.andTrainDateBetween(DateUtil.String2Date(requestGear.getStartTime()),
                    DateUtil.String2Date(requestGear.getEndTime()));

            if(requestGear.getTrainId() != null){
                criteria.andTrainIdEqualTo(requestGear.getTrainId());
            }

            if(requestGear.getTrainDirection() != null){
                criteria.andTrainDirectionEqualTo(requestGear.getTrainDirection());
            }

            List<TrainInfo> infos = trainInfoMapper.selectByExample(example);
            if(infos.size()==0){
                return ResultVO.createByErrorMessage("无数据");
            }
            PageInfo<TrainInfo> pageInfo = new PageInfo<>(infos);

            assembleGearTrendencyInfo(requestGear, gearList, infos);
            PageResultVo pageResultVo = new PageResultVo();
            PageUtils.pageUtil(pageInfo,pageResultVo);
            pageResultVo.setList(gearList);
            return ResultVO.createBySuccess(pageResultVo);
        }
    }
//现在这个方法里出了一些问题
    private void assembleGearTrendencyInfo(RequestGear requestGear, List<GearResponse> gearList, List<TrainInfo> infos) {
        for(TrainInfo info : infos){
            GearResponse gear = new GearResponse();
            gear.setTrainId(info.getTrainId());
            gear.setTrainDate(DateUtil.Date2String(info.getTrainDate()));
            gear.setTrainDirection(info.getTrainDirection());
            gear.setTrainStation(info.getTrainStation());
            gear.setMotorNum(requestGear.getMotorNum());
            gear.setGearNum1(requestGear.getGearNum1());
            gear.setGearNum2(requestGear.getGearNum2());
            MotorInfo motorInfo =
                    motorInfoMapper.findByTrainIdAndMotorNum(info.getTrainOnlyid(),requestGear.getMotorNum());
            if(motorInfo.getMotorId()!=null){
                GearInfo gearInfo1 = gearInfoMapper.findByMotorIdAndGearNum(motorInfo.getMotorId(),requestGear.getGearNum1());
                gear.setLeftGear1(gearInfo1.getLgapValue());
                gear.setRightGear1(gearInfo1.getRgapValue());

                GearInfo gearInfo2 = gearInfoMapper.findByMotorIdAndGearNum(motorInfo.getMotorId(),requestGear.getGearNum2());
                gear.setLeftGear2(gearInfo2.getLgapValue());
                gear.setRightGear2(gearInfo2.getRgapValue());
                gearList.add(gear);
            }else {
                continue;
            }
        }
    }

}
